import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { WagesEntity } from '@entity/jx3/wages.entity';
import {
  ListWagesDTO,
  CreateWagesDTO,
  UpdateWagesDTO,
} from '@dto/jx3/wages.dto';
import { resBuild } from '@utils/resBuild';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { getOperator, getTimeFormat, getUserId, getUUID } from '@utils';
import { JwtService } from '@midwayjs/jwt';

@Provide()
export class WagesService {
  @Inject()
  ctx: Context;

  @Inject()
  jwtService: JwtService;

  @InjectEntityModel(WagesEntity)
  WagesEntity: Repository<WagesEntity>;

  // 列表
  async list(queryParams: ListWagesDTO) {
    const queryBuilder = this.WagesEntity.createQueryBuilder('entity');

    // 添加按创建时间排序，默认降序（最新的在前）
    queryBuilder.orderBy('entity.createTime', 'DESC');

    if (queryParams.pageNum && queryParams.pageSize) {
      queryBuilder
        .skip((queryParams.pageNum - 1) * queryParams.pageSize)
        .take(queryParams.pageSize);
    }

    const [rows, total] = await queryBuilder.getManyAndCount();
    return resBuild.list(rows, total);
  }

  // 添加
  async create(Wages: CreateWagesDTO) {
    // 新增
    Wages.userId = getUserId(this.ctx);
    Wages.id = getUUID();
    const myEntity = this.WagesEntity.create(Wages);
    myEntity.setCreateBy(getOperator(this.ctx));
    myEntity.setUpdateBy(getOperator(this.ctx));
    myEntity.setCreateTime(getTimeFormat());
    myEntity.setUpdateTime(getTimeFormat());
    await this.WagesEntity.save(myEntity);
    return resBuild.success();
  }

  // 删除
  async delete(id: string) {
    const ids = id.split(',').map(id => Number(id));
    await this.WagesEntity.delete(ids);
    return resBuild.success();
  }

  // 修改
  async update(Wages: UpdateWagesDTO) {
    const myEntity = this.WagesEntity.create(Wages);
    myEntity.setUpdateBy(getOperator(this.ctx));
    myEntity.setUpdateTime(getTimeFormat());
    await this.WagesEntity.save(myEntity);
    return resBuild.success();
  }

  // 详情
  async detail(id: string) {
    const detailInfo = await this.WagesEntity.findOneBy({
      id,
    });
    return resBuild.data(detailInfo);
  }
  // 详情
  async getWagesDetail() {
    // 从请求头或请求参数中获取token
    const token = this.ctx.headers.authorization?.split(' ')[1]; // 假设token在Authorization头中，格式为Bearer <token>
    const decoded: any = await this.jwtService.verify(token, {
      complete: true,
    });
    let userId = decoded.payload.userId;
    console.log(userId);
    // 新增之前先判断是否已存在
    const isExist: ListWagesDTO = await this.WagesEntity.findOneBy({
      ['userId']: userId,
    });
    return resBuild.data(isExist);
  }
}
